﻿function writeCookie(name, value, days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for (i = 0; i < ca.length; i++) {
        c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }

        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }

    return '';
}

function get_browser() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE ' + (tem[1] || '');
    }

    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR\/(\d+)/)
        if (tem != null) {
            return 'Opera ' + tem[1];
        }
    }

    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
        M.splice(1, 1, tem[1]);
    }

    return M[0];
}

function get_browser_version() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE ' + (tem[1] || '');
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR\/(\d+)/)
        if (tem != null) {
            return 'Opera ' + tem[1];
        }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
        M.splice(1, 1, tem[1]);
    }
    return M[1];
}

// Define symbol "Z" like "$" in jQuery
var Z = function (s) {
    // Save list of Elements
    var ZResultList = document.querySelectorAll(s);

    // Save Element
    var ZResult;

    if (ZResultList.length == 1) {
        ZResult = ZResultList[0];
    }

    // Get length
    this.length = function () {
        return ZResultList.length;
    };

    // Get Type
    this.getType = function () {
        return ZResult.type;
    };

    // Get Element
    this.selectElement = function (pos) {
        switch (pos) {
            case "first":
                ZResult = ZResultList[0];
                break;
            case "last":
                ZResult = ZResultList[ZResultList.length - 1];
                break;
            default:
                if (pos <= ZResultList.length - 1) {
                    ZResult = ZResultList[pos];
                }
                else {
                    ZResult = ZResultList[0];
                }
                break;
        }

        return this;
    };

    // Get Text
    this.getText = function () {
        if (get_browser() == "Firefox") {
            return ZResult.textContent;
        }
        else {
            return ZResult.innerText;
        }
    };

    // Set Text
    this.setText = function (data) {
        if (get_browser() == "Firefox") {
            ZResult.textContent = data;
        }
        else {
            ZResult.innerText = data;
        }
        return this;
    };

    // Get HTML
    this.innerHTML = function () {
        return ZResult.innerHTML;
    };

    // Set HTML
    this.setHTML = function (data) {
        ZResult.innerHTML = data;

        return this;
    };

    // Add Class
    this.addClass = function (name) {
        if (ZResult.className !== "") {
            ZResult.className += " " + name;
        }
        else {
            ZResult.className = name;
        }

        return this;
    };

    // Remove Class
    this.removeClass = function (name) {
        var remClass = ZResult.className;
        var re = new RegExp('(^| )' + name + '( |$)');
        remClass = remClass.replace(re, '$1');
        remClass = remClass.replace(/ $/, '');
        ZResult.className = remClass;

        return this;
    };

    // Toggle Class
    this.toggleClass = function (c1, c2) {
        var t = ZResult.className;
        if (ZResult.className.search(c1) != -1) {
            this.removeClass(c1);
            this.addClass(c2);
        } else {
            if (ZResult.className.search(c2) != -1) {
                this.removeClass(c2);
                this.addClass(c1);
            }
            else {
                this.addClass(c1);
            }
        }

        return this;
    };

    // Add Attribute
    this.addAttribute = function (name, value) {
        ZResult.setAttribute(name, value);

        return this;
    };

    // Remove Attribute
    this.removeAttribute = function (name) {
        ZResult.removeAttribute(name);

        return this;
    };

    // Get Width
    this.getWidth = function () {
        return ZResult.offsetWidth;
    };

    // Get Height
    this.getHeight = function () {
        return ZResult.offsetHeight;
    };

    // onClick
    this.onClick = function (f) {
        if (ZResult.addEventListener) { // use addEventListener for DOM
            ZResult.removeEventListener('click', f, false);
            ZResult.addEventListener('click', f, false);
        } else if (ZResult.attachEvent) { // use attachEvent for IE
            ZResult.detachEvent('onclick', f);
            ZResult.attachEvent('onclick', f);
        }

        return this;
    };

    // onLoad
    this.onLoad = function (f) {
        if (this.addEventListener) { // use addEventListener for DOM
            this.addEventListener('load', f, false);
        } else if (this.attachEvent) { // use attachEvent for IE
            this.attachEvent('onload', f);
        }
    };

    // Set Src
    this.setSrc = function (imagePath) {
        ZResult.src = imagePath;
    };

    // Set Style
    this.setStyle = function (style, value) {
        ZResult.style[style.toString()] = value.toString();
    };

    // Toggle Style
    this.toggleStyle = function (style, v1, v2) {
        if (ZResult.style[style] == v1) {
            this.setStyle(style, v2);
        } else {
            this.setStyle(style, v1);
        }
    };

    // Set Value
    this.setValue = function (data) {
        ZResult.value = data;
    };

    // Get Value
    this.getValue = function () {
        return ZResult.value;
    };

    // Get value
    this.getValueFromSelection = function () {
        return ZResult.options[ZResult.selectedIndex].value;
    }
    return this;
};

// Write HTML
Z.writeHTML = function (data) {
    document.write(data);
};

// Get Window Height
Z.getWindowHeight = function () {
    return window.screen.availHeight;
};

// Get Window Width
Z.getWindowWidth = function () {
    return window.screen.availWidth;
};

// Set Local Storage
Z.setLocalStorage = function (name, value, days) {

    var data;
    if (typeof (value) == "object") {
        data = JSON.stringify(value);
    }
    else {
        data = value;
    }
    if (get_browser() == 'MSIE' && get_browser_version() == '7') {

        writeCookie(name, data, days);
    }
    else {
        localStorage.setItem(name, data);
    }
};

// Get Local Storage
Z.getLocalStorage = function (name) {

    if (get_browser() == 'MSIE' && get_browser_version() == '7') {

        return readCookie(name);
    }

    return localStorage.getItem(name);
};

// Remove Local Storage
Z.prototype.removeLocalStorage = function (name) {
    if (get_browser() == 'MSIE' && get_browser_version() == '7') {
        eraseCookie(name);
    } else {
        localStorage.removeItem(name);
    }
};

// AJAX
Z.ajax = function (s) {
    var xmlhttp;


    var url = s["url"];
    var type = s["type"];

    var data = s["data"];
    if (typeof (data) == "string") {
        data = "text=" + data;
    }

    var dataType = s["dataType"];

    var success = s["success"];
    var loading = s["loading"];
    var error = s["error"];


    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if (success != null)
                success(xmlhttp.responseText);
        }

        if (xmlhttp.status == 404) {
            if (error != null)
                error(xmlhttp.responseText);
        }

        if (xmlhttp.readyState == 3) {
            if (loading != null) {
                loading(xmlhttp.responseText);
            }
        }

    }

    if (type == "GET") {
        xmlhttp.open("GET", url, true);
    }
    else {
        xmlhttp.open("POST", url, true);
    }


    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");


    if (dataType == "JSON" && data != null)
        xmlhttp.send("JSON=" + JSON.stringify(data));
    else
        xmlhttp.send(data);

}